﻿#region - Class details -
/*  
 *  Developer   :Tony Hicks
 *  Description : 
 *  History     :
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace QuickApp.Helpers
{
    public static class DataTableHelper
    {
        public static DataTable GetTableFromIEnum(IEnumerable<object> objList)
        {
            DataTable dt = new DataTable();
            foreach (object obj in objList)
            {
                Type objType = obj.GetType();
                PropertyInfo[] objProperties = objType.GetProperties();
                if (dt.Columns.Count == 0)
                {
                    foreach (PropertyInfo pi in objProperties)
                    {
                        //You have to use the Nullable.GetUnderlyingType method because the datatable doesn't recognize nullable types.
                        //If that returns null, then it is not a nullable type and the null-coalescing operator (??) will use the 
                        //property type (LHS != null ? LHS : RHS;) => (LHS ?? RHS;) .
                        dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType);
                    }
                }
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo property in objProperties)
                {
                    object value = property.GetValue(obj, null);
                    dr[property.Name] = value ?? DBNull.Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
        /// <summary>
        /// Returns a DataTable with the Properties of the given object as it's schema
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DataTable GetTableSchemaFromObject(object obj)
        {
            DataTable dt = new DataTable();
            Type objType = obj.GetType();
            var objProperties = objType.GetProperties();
            foreach (PropertyInfo property in objProperties)
            {
                dt.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }
            return dt;
        }
        public static DataTable GetDistinctDataTable(this DataTable dt, params string[] distinctColNames)
        {
            var distinctTable = new DataView(dt);
            return distinctTable.ToTable(true, distinctColNames);
        }
    }
}
